import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../models/category.dart';
import '../models/todo_item.dart';
import 'category_actions_widget.dart';

/// 分类树形组件
class CategoryTreeWidget extends StatefulWidget {
  final List<Category> categories;
  final String? selectedCategoryId;
  final Function(String?) onCategorySelected;
  final Function(String todoId, String categoryId)? onTodoDrop;
  final VoidCallback? onAddCategory; // 新增分类回调
  final VoidCallback? onEditCategory; // 编辑分类回调
  final VoidCallback? onDeleteCategory; // 删除分类回调
  final VoidCallback? onRefreshCategory; // 刷新分类回调
  final Function(String categoryId, String targetCategoryId)? onCategoryDrop; // 分类拖拽回调(旧的,改变父级)
  final Function(String categoryId, String targetId, String dropType)? onCategoryDrag; // 分类拖拽排序回调(新的)

  const CategoryTreeWidget({
    super.key,
    required this.categories,
    this.selectedCategoryId,
    required this.onCategorySelected,
    this.onTodoDrop,
    this.onAddCategory,
    this.onEditCategory,
    this.onDeleteCategory,
    this.onRefreshCategory,
    this.onCategoryDrop,
    this.onCategoryDrag,
  });

  @override
  State<CategoryTreeWidget> createState() => _CategoryTreeWidgetState();
}

class _CategoryTreeWidgetState extends State<CategoryTreeWidget> {
  final Set<String> _expandedCategories = {};

  @override
  void initState() {
    super.initState();
    // 初始化时展开选中分类的路径
    _expandPathToSelectedCategory();
    // 如果没有选中分类，则展开第一项
    _expandFirstCategoryIfNeeded();
  }

  @override
  void didUpdateWidget(CategoryTreeWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 当选中的分类改变时，或分类列表从空变为有数据时，展开其路径
    if (oldWidget.selectedCategoryId != widget.selectedCategoryId ||
        (oldWidget.categories.isEmpty && widget.categories.isNotEmpty)) {
      _expandPathToSelectedCategory();
      // 如果没有选中分类，则展开第一项
      _expandFirstCategoryIfNeeded();
    }
  }

  /// 展开到选中分类的路径
  void _expandPathToSelectedCategory() {
    if (widget.selectedCategoryId == null) return;
    if (widget.categories.isEmpty) return; // 如果分类列表为空，不处理

    final path = _findCategoryPath(widget.categories, widget.selectedCategoryId!);
    if (path.isNotEmpty) {
      setState(() {
        // 展开路径上的所有父分类（不包括自己）
        for (int i = 0; i < path.length - 1; i++) {
          _expandedCategories.add(path[i]);
        }
      });
    }
  }

  /// 如果没有选中分类，自动展开第一项
  void _expandFirstCategoryIfNeeded() {
    // 如果已经有选中的分类，不自动展开
    if (widget.selectedCategoryId != null) return;
    // 如果分类列表为空，不处理
    if (widget.categories.isEmpty) return;

    // 展开第一项分类
    final firstCategory = widget.categories.first;
    if (firstCategory.children.isNotEmpty) {
      setState(() {
        _expandedCategories.add(firstCategory.id);
      });
    }
  }

  /// 查找分类的路径（返回从根到目标的所有分类ID）
  List<String> _findCategoryPath(List<Category> categories, String targetId, [List<String> currentPath = const []]) {
    for (final category in categories) {
      final newPath = [...currentPath, category.id];

      if (category.id == targetId) {
        return newPath;
      }

      if (category.children.isNotEmpty) {
        final result = _findCategoryPath(category.children, targetId, newPath);
        if (result.isNotEmpty) {
          return result;
        }
      }
    }
    return [];
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xFFF7F7F7),
      child: Column(
        children: [
          // 第一行：macOS 窗口操作栏占位（不显示内容，只留空间）
          if (Platform.isMacOS)
            const SizedBox(height: 40), // 为窗口控制按钮预留空间


          // 【分类操作区域】- 新增、编辑、删除、刷新分类
          CategoryActionsWidget(
            onAdd: widget.onAddCategory,
            onEdit: widget.onEditCategory,
            onDelete: widget.onDeleteCategory,
            onRefresh: widget.onRefreshCategory,
            hasSelectedCategory: widget.selectedCategoryId != null &&
                                 widget.selectedCategoryId != '-1' &&
                                 widget.selectedCategoryId != '-2',
          ),

          // 第四行：分类树列表（无背景）
          Expanded(
            child: ListView(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              children: widget.categories.map((category) {
                return _buildCategoryItem(category, 0);
              }).toList(),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCategoryItem(Category category, int level) {
    final isExpanded = _expandedCategories.contains(category.id);
    final isSelected = widget.selectedCategoryId == category.id;
    final hasChildren = category.children.isNotEmpty;

    // macOS平台支持拖拽
    final categoryItem = Column(
      children: [
        // 上方插入区域 - 拖到这里表示插入到 category 前面
        DragTarget<Object>(
          onWillAcceptWithDetails: (details) {
            if (details.data is Category) {
              return (details.data as Category).id != category.id;
            }
            return false; // TodoItem 不支持拖到插入区
          },
          onAcceptWithDetails: (details) {
            if (details.data is Category && widget.onCategoryDrag != null) {
              widget.onCategoryDrag!(
                (details.data as Category).id,
                category.id,
                'before', // 插入到前面
              );
            }
          },
          builder: (context, candidateData, rejectedData) {
            final isDraggingOver = candidateData.isNotEmpty;
            return Container(
              height: isDraggingOver ? 4 : 2,
              margin: const EdgeInsets.symmetric(horizontal: 8),
              decoration: BoxDecoration(
                color: isDraggingOver ? Colors.blue : Colors.transparent,
                borderRadius: BorderRadius.circular(2),
              ),
            );
          },
        ),

        // 中间主体区域 - 拖到这里表示成为子分类或待办分类
        DragTarget<Object>(
          onWillAcceptWithDetails: (details) {
            // 接受TodoItem或Category
            if (details.data is TodoItem) {
              return true;
            } else if (details.data is Category) {
              // 不能拖拽到自己
              return (details.data as Category).id != category.id;
            }
            return false;
          },
          onAcceptWithDetails: (details) {
            if (details.data is TodoItem) {
              // 待办拖拽到分类
              if (widget.onTodoDrop != null) {
                widget.onTodoDrop!((details.data as TodoItem).id, category.id);
              }
            } else if (details.data is Category) {
              // 分类拖拽到分类 - 使用新的拖拽接口
              if (widget.onCategoryDrag != null) {
                widget.onCategoryDrag!(
                  (details.data as Category).id,
                  category.id,
                  'inner', // 成为子分类
                );
              }
            }
          },
          builder: (context, candidateData, rejectedData) {
            final isDraggingOver = candidateData.isNotEmpty;

            return Container(
              margin: const EdgeInsets.symmetric(vertical: 2),
              decoration: BoxDecoration(
                color: isDraggingOver
                    ? Colors.blue[100]
                    : (isSelected ? const Color(0xFFE8E8E8) : null),
                borderRadius: BorderRadius.circular(10),
                border: isDraggingOver
                    ? Border.all(color: Colors.blue, width: 2)
                    : null,
              ),
              child: ListTile(
                dense: true,
                contentPadding: EdgeInsets.only(
                  left: 16.0 + (level * 12.0),
                  right: 16.0,
                ),
                horizontalTitleGap: 10, // 文件夹图标和分类名之间的间距
                leading: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    if (hasChildren)
                      InkWell(
                        onTap: () {
                          setState(() {
                            if (isExpanded) {
                              _expandedCategories.remove(category.id);
                            } else {
                              _expandedCategories.add(category.id);
                            }
                          });
                        },
                        child: Icon(
                          isExpanded ? Icons.expand_more : Icons.chevron_right,
                          size: 16,
                          weight: 300,
                        ),
                      )
                    else
                      const SizedBox(width: 16),
                    const SizedBox(width: 4), // 展开图标和文件夹图标之间的间距
                    SvgPicture.asset(
                      'assets/icons/folder.svg',
                      width: level == 0 ? 18.0 : 16.0,
                      height: level == 0 ? 18.0 : 16.0,
                    ),
                  ],
                ),
                title: Text(
                  category.name,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                    color: isSelected ? Colors.grey[800] : null,
                  ),
                ),
                onTap: () {
                  // 如果有子分类且未展开，则展开
                  if (hasChildren && !isExpanded) {
                    setState(() {
                      _expandedCategories.add(category.id);
                    });
                  }
                  // 选择该分类
                  widget.onCategorySelected(category.id);
                },
              ),
            );
          },
        ),

        // 下方插入区域 - 拖到这里表示插入到 category 后面
        DragTarget<Object>(
          onWillAcceptWithDetails: (details) {
            if (details.data is Category) {
              return (details.data as Category).id != category.id;
            }
            return false; // TodoItem 不支持拖到插入区
          },
          onAcceptWithDetails: (details) {
            if (details.data is Category && widget.onCategoryDrag != null) {
              widget.onCategoryDrag!(
                (details.data as Category).id,
                category.id,
                'after', // 插入到后面
              );
            }
          },
          builder: (context, candidateData, rejectedData) {
            final isDraggingOver = candidateData.isNotEmpty;
            return Container(
              height: isDraggingOver ? 4 : 2,
              margin: const EdgeInsets.symmetric(horizontal: 8),
              decoration: BoxDecoration(
                color: isDraggingOver ? Colors.blue : Colors.transparent,
                borderRadius: BorderRadius.circular(2),
              ),
            );
          },
        ),

        if (isExpanded && hasChildren)
          ...category.children.map((child) {
            return _buildCategoryItem(child, level + 1);
          }),
      ],
    );

    // macOS平台支持拖拽分类
    if (Platform.isMacOS && widget.onCategoryDrag != null) {
      return Draggable<Category>(
        data: category,
        feedback: Material(
          elevation: 8,
          child: Container(
            width: 180,
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.blue, width: 2),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                SvgPicture.asset(
                  'assets/icons/folder.svg',
                  width: 16,
                  height: 16,
                ),
                const SizedBox(width: 8),
                Flexible(
                  child: Text(
                    category.name,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
          ),
        ),
        childWhenDragging: Opacity(
          opacity: 0.3,
          child: categoryItem,
        ),
        child: categoryItem,
      );
    }

    return categoryItem;
  }
}
